<?php

/**
 * Description of Web
 *
 * @author ananda
 */
class App_Service extends App
{
    const RESPONSE_JSON = 'JSON';
    const RESPONSE_YAML = 'YAML';
    const RESPONSE_XML  = 'XML';

    const PROTOCOL_RPC  = 'RPC';
    const PROTOCOL_REST = 'REST';

    public $response_type = self::RESPONSE_JSON;
    public $protocol_type = self::PROTOCOL_RPC;

    public function init() {}

    public function main($options = array())
    {
        $key = isset($options['key']) ? $options['key'] : 'r';

        // 先随便写写
        $exception_classname = "Exception_Response_".
                                ucfirst(strtolower($this->response_type)).
                                ucfirst(strtolower($this->protocol_type));
        $this->route($key);

        try {
            $this->controller = $this->createController($this->controller);
        } catch (Exception $e) {
            echo new $exception_classname($e->getMessage());
            die();
        }
        
        try {
            $this->action = $this->createAction($this->controller, $this->action, $this->params);
        } catch (Exception $e) {
            if ($this->controller instanceof Controller_Service) {
                echo new $exception_classname($e->getMessage());
            } else {
                echo "<pre>$e</pre>";
            }
            die();
        }

        if ($this->controller instanceof Controller_Service) {

            $handler = strtolower($this->response_type).
                       ucfirst(strtolower($this->protocol_type)).'Handle';
            try {
                $this->$handler($this->action);
            } catch (Exception_Response $e) {
                echo $e;
                die();
            } catch (Exception $e) {
                echo new $exception_classname($e->getMessage());
            }

        } else {
            $this->action->main();
        }
        
    }

    public function route($key = 'r')
    {
        // 先随便写写
        $temp = explode('/', Request::get($key, Com::glob('com.default_controller')));

        $this->controller = ucfirst($temp[0]);
        $this->action     = isset($temp[1]) ? ucfirst(strtolower($temp[1])) : null;

        unset($temp[0]);
        unset($temp[1]);
        $this->params = $temp;
    }

    /**
     * 这才是真正随便写写的方法
     * @param <type> $object
     */
    public function jsonRpcHandle($object)
    {
        if (!jsonRPCServer::handle($object)) {
            throw new Exception_Response_JsonRpc('Request is failure');
        }
    }
}
